Goods[]
Goods
Objects
public class StoreArray
{
public static void main ( String[] args )
{
Goods[] inventory = new Goods[10];
inventory[0] = new Goods( "bubble bath", 1.40 );
inventory[1] = new Food ( "ox tails", 4.45, 1500 );
inventory[2] = new Book ( "Emma", 24.95, "Austen" );
inventory[3] = new Toy ( "Leggos", 54.45, 8 );
inventory[0].display();
inventory[1].display();
inventory[2].display();
inventory[3].display();
}
}
The modified testing program uses an array.
Since each child class is-a Goods
,
an array of type Goods[]
can be used for any of them.
The array inventory
has 10 cells,
but the program uses only 4 of them.
Each cell of the array is a reference variable which can refer to an object of type Goods or to any derived class of Goods.
Here is the output of the program:
C:\Temp>javac StoreArray.java C:\Temp>java StoreArray item: bubble bath price: 1.4 item: ox tails price: 4.45 calories: 1500.0 item: Emma price: 24.95 author: Austen item: Leggos price: 54.45 minimum age: 8
(Review:) Does this line:
inventory[1].display();
execute the same display()
method as this line:
inventory[2].display();